package ysf.com.mediumdifficulty;

import java.util.HashSet;
import java.util.Set;

/**
 * 给定一个字符串找到没有重复字符的最长字符串，返回它的长度
 * @author ysf
 * @date 2021/6/7 23:24
 */
public class ThirdDemo {

    public static void main(String[] args) {
        String str="abbcdeffguioytrew";
        /*int i = lengthOfLongestSubstring(str);
        System.out.println(i);*/

        int i1 = lengthOfLongestSubstringFourth(str);
        System.out.println(i1);
    }
    /**
     * 解法一
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring(String s){
        int n = s.length();  // 字符串的长度
        int ans = 0;  // 保存当前得到满足条件的字串的最大值
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j <=n; j++) {
                if(allUnique(s,i,j)) ans = Math.max(ans,j-i);  // 更新ans
            }
        }
        return ans;
    }
    public static boolean allUnique(String s ,int start,int end){
        Set<Character> set = new HashSet<Character>();    // 初始化hash set
        for (int i = start; i < end; i++) {   // 遍历每个字符
            Character ch = s.charAt(i);
            if(set.contains(ch)) return false;   // 判断字符在不在 set 中
            set.add(ch); // 不在的话将该字符串添加到set里边
        }
        return true;
    }

    // 解法四
    public static int lengthOfLongestSubstringFourth(String s){

        /*int [] indexs = new int[128];
        String strs="abbcd";
        int length = strs.length();
        for (int i =0,m=0;i<length;i++){
            char c = strs.charAt(i);
            int ss =indexs[c];
            System.out.println(ss);
        }*/
       /* char cs = strs.charAt(2);
        System.out.println(cs);
        int ss =indexs[c];
        System.out.println(ss);
        int sss =indexs[cs];
        System.out.println(sss);*/
       //s ="abbcddfghhop";

        int[] indexs = new int[5];

        String[] strsArray = new String[]{"a","b","c","d","e"};

       s ="aabcd";
        int n = s.length(), ans = 0;
        int[] index = new int[128];
        for (int j = 0, i = 0; j < n; j++) {
            char c = s.charAt(j);
            int m = index[c];
            i = Math.max(m, i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;  //（下标 + 1） 代表 i 要移动的下个位置
            //int k = index[s.charAt(j)];
            //System.out.println(k);

        }
        return ans;
        //return 2;
    }



}
